package com.dede.monochromatism.broadcast

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v4.content.ContextCompat
import com.dede.applib.extends.getBoolean
import com.dede.monochromatism.S_PRE_STATUS
import com.dede.monochromatism.S_PRE_TIME
import com.dede.monochromatism.db.PackageDatabaseOpenHelper.Companion.packageName
import com.dede.monochromatism.service.DbLoaderService
import com.dede.monochromatism.service.TimeJobService
import com.dede.monochromatism.util.ShellUtil
import com.dede.monochromatism.util.Util
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.startService
import org.jetbrains.anko.uiThread

/**
 * @author hsh
 * @time 2017/6/25 025 8:34 上午.
 * @doc
 */
class BootBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {
        if (Intent.ACTION_BOOT_COMPLETED == intent?.action) {
            //是否有修改系统安全设置的权限
            val hasPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_SECURE_SETTINGS)
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                doAsync({ it.printStackTrace() }) {
                    val hasSU = ShellUtil.requestRoot()//请求root权限
                    if (hasSU) {
                        ShellUtil.requestPermission(packageName)
                        uiThread {
                            init(context)
                        }
                    }
                }
            } else {
                init(context)
            }
        }
    }

    private fun init(context: Context) {
        var state = context.getBoolean(S_PRE_STATUS, false)
        if (state) {
            Util.openAccessibilitySettings(context)
            context.startService<DbLoaderService>()
        } else {
            Util.closeAccessibilitySettings(context)
        }
        state = context.getBoolean(S_PRE_TIME, false)
        if (state)
            TimeJobService.registerJob(context)
    }
}